/**
 * @author: dn-jinmin/dn-jinmin
 * @doc:
 */

package main

import (
	"fmt"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"strconv"
)

type Person struct {
	Name  string
	Phone string
	Email string
	Age   int
	Other string
}

func main() {

	execlPath := "test.xlsx"

	persons := []Person{
		{Name: "Tom", Phone: "138888", Email: "tom@example.com", Age: 20, Other: "other"},
		{Name: "Jerry", Phone: "13999999999", Email: "jerry@example.com", Age: 22, Other: "other"},
	}

	// 创建一个新的空工
	file := excelize.NewFile()

	// 新建一个 Sheet，命名为 Sheet1
	sheetName := "Sheet1"
	streamWriter, err := file.NewStreamWriter(sheetName)
	if err != nil {
		fmt.Println(err)
		return
	}

	// 写入字段属性行，从 A1 开始
	if err := streamWriter.SetRow("A1", []interface{}{"name", "phone", "email", "age", "other"}); err != nil {
		panic(err)
	}
	rows := 2
	// 写入数据行
	for _, person := range persons {
		if err := streamWriter.SetRow("A"+strconv.Itoa(rows), []interface{}{person.Name, person.Phone, person.Email, person.Age, person.Other}); err != nil {
			panic(err)
		}
		rows++
	}

	// 设置生成的 Excel 文件的默认 Sheet
	if err := streamWriter.Flush(); err != nil {
		panic(err)
	}

	// 保存 Excel 文件
	if err := file.SaveAs(execlPath); err != nil {
		panic(err)
	}
}
